//
//  GXLinkViewController.m
//

#import "GXLinkViewController.h"
#import "GXLinkCell.h"
#import "GXLinkHeader.h"

#import "GXGradientView.h"

#define linkPrefixCellId @"linkPrefixCellId"
#define linkPrefixHeaderId @"linkPrefixHeaderId"

#define linkPrefixAnotherCellId @"linkPrefixAnotherCellId"
#define linkPrefixAnotherHeaderId @"linkPrefixAnotherHeaderId"

#define linkContentCellId @"linkContentCellId"
#define linkContentHeaderId @"linkContentHeaderId"

#define linkContentAnotherCellId @"linkContentAnotherCellId"
#define linkContentAnotherHeaderId @"linkContentAnotherHeaderId"

#define headerHeight 22

@interface GXLinkViewController () <UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

@property (nonatomic, weak) UITableView *tvPrefix;
@property (nonatomic, weak) UITableView *tvContent;

@property (nonatomic, assign) CGFloat preHeight;
@property (nonatomic, assign) CGFloat conHeight;


@property (nonatomic, weak) UIScrollView *svContent;
@property (nonatomic, weak) UIView *vSize;

//
//@property (nonatomic, weak) UIView *vGuidLeft;
//@property (nonatomic, weak) UIView *vGuidRight;

@property (nonatomic, weak) GXGradientView *vGradientLeft;
@property (nonatomic, weak) GXGradientView *vGradientRight;

//@property (nonatomic, weak) UIView *vGuidLineLeft;
//@property (nonatomic, weak) UIView *vGuidLineRight;

//@property (nonatomic, strong) CAGradientLayer *gradientLeftLayer;
//@property (nonatomic, strong) CAGradientLayer *gradientRightLayer;

@property (nonatomic, assign) CGFloat originTranlationX;

@property(nonatomic, assign) CGFloat currentTranslationX;
@property(nonatomic, assign) BOOL isBegan;


@end

@implementation GXLinkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //
    [self setupUI];
}

#pragma mark - Actions
- (void)panHorizontalAction:(UIPanGestureRecognizer *)pan {
    CGPoint translation = [pan translationInView:self.view];
    _originTranlationX += translation.x;
    //    NSLog(@"%@", @(_originTranlationX).description);
    
    [pan setTranslation:CGPointZero inView:self.view];
    //    NSLog(@"translation: %@", NSStringFromCGPoint(translation));
    
    if (ABS(translation.y) > ABS(translation.x)) {
        return;
    }
    
    CGFloat offsetX = self.svContent.contentOffset.x - translation.x;
    CGFloat scale = translation.x / self.view.bounds.size.width * 1.0;
    CGFloat offsetWidth = self.svContent.contentSize.width - self.svContent.bounds.size.width;
    
    //    NSLog(@"self.svContent.contentOffset: %@", [NSValue valueWithCGPoint:self.svContent.contentOffset]);
    
//    NSLog(@"-----translation.x: %@", @(translation.x).description);
//    NSLog(@"self.svContent.contentOffset.x: %@", @(self.svContent.contentOffset.x).description);
//    NSLog(@"offsetX: %@", @(offsetX).description);
    //        NSLog(@"offsetWidth: %@", @(offsetWidth).description); //473
    
    
    if (offsetX <= 0 || offsetX >= offsetWidth) {
        
        //这个ended里面的代码好像是多余的了。 -by gcx 2017-06-03
        if (pan.state == UIGestureRecognizerStateEnded) {
            [self.vGradientLeft startGradientAnimation];
            [self.vGradientRight startGradientAnimation];
        }
        
        //gradient view
        self.isBegan = NO;
        if (_currentTranslationX == 0) {
            self.isBegan = YES;
        }
        _currentTranslationX = translation.x;
        
//        NSLog(@"isBegan: %@", @(self.isBegan).description);
//        NSLog(@"state: %@", @(pan.state).description);
        
        if (offsetX <= 0 && scale > 0) { //gradient left
            
            [self.svContent setContentOffset:CGPointMake(0, 0) animated:NO];
            [self setGradientLeftWithPan:pan scale:scale isBegan:self.isBegan];
        }else if (offsetX > offsetWidth && scale < 0) { //gradient right
            
            [self.svContent setContentOffset:CGPointMake(offsetWidth, 0) animated:NO];
            [self setGradientRightWithPan:pan scale:scale isBegan:self.isBegan];
        }
        self.isBegan = NO;
        return;
    }
    
    [self.svContent setContentOffset:CGPointMake(offsetX, 0) animated:NO];
    //    NSLog(@"svContent.contentOffset: %@", NSStringFromCGPoint(self.svContent.contentOffset));
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        _originTranlationX = 0;
    }
}

- (void)setGradientLeftWithPan:(UIPanGestureRecognizer *)pan scale:(CGFloat)scale isBegan:(BOOL)isBegan {
    if (pan.state == UIGestureRecognizerStateBegan || isBegan) {
        [self.vGradientLeft prepareGradientAnimation];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.vGradientLeft startGradientAnimation];
        });
    }
    
    if (pan.state == UIGestureRecognizerStateBegan || pan.state == UIGestureRecognizerStateChanged) {
        self.vGradientLeft.scale = scale;
    }
}

- (void)setGradientRightWithPan:(UIPanGestureRecognizer *)pan scale:(CGFloat)scale isBegan:(BOOL)isBegan {
    if (pan.state == UIGestureRecognizerStateBegan || isBegan) {
        [self.vGradientRight prepareGradientAnimation];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.vGradientRight startGradientAnimation];
        });
    }
    
    if (pan.state == UIGestureRecognizerStateBegan || pan.state == UIGestureRecognizerStateChanged) {
        self.vGradientRight.scale = scale;
    }
}



#pragma mark - methods
- (void)reloadTvs {
    [self.tvPrefix reloadData];
    [self.tvContent reloadData];
}

- (void)reload {
    [self reloadTvs];
}





#pragma mark - delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 0;
    if (tableView == _tvPrefix) {
        count = self.tvPrefixList.count;
    }else {
        count = self.tvContentList.count;
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GXLinkCell *cell = nil;
    if (tableView == _tvPrefix) {
        if (self.isNeedCreate) {
            cell = [tableView dequeueReusableCellWithIdentifier:linkPrefixAnotherCellId forIndexPath:indexPath];
        } else {
            cell = [tableView dequeueReusableCellWithIdentifier:linkPrefixCellId forIndexPath:indexPath];
        }
        cell.viewcontrollerEnum = self.viewcontrollerEnum;
        cell.isPrefix = YES;
        cell.linkCellList = self.tvPrefixList[indexPath.row];
        
        _preHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        
        //NSLog(@"_tvPrefix_preHeight---cell.height: %@, row: %@", @(_preHeight).description, @(indexPath.row).description);
    }else {
        if (self.isNeedCreate) {
            cell = [tableView dequeueReusableCellWithIdentifier:linkContentAnotherCellId forIndexPath:indexPath];
        } else {
            cell = [tableView dequeueReusableCellWithIdentifier:linkContentCellId forIndexPath:indexPath];
        }
        cell.viewcontrollerEnum = self.viewcontrollerEnum;
        cell.isPrefix = NO;
        cell.linkCellList = self.tvContentList[indexPath.row];
        
        _conHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        
        //NSLog(@"_tvContent_conHeight---cell.height: %@, row: %@", @(_conHeight).description, @(indexPath.row).description);
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return MAX(_preHeight, _conHeight);
}

//Header
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return headerHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    GXLinkHeader *header = nil;
    if (tableView == _tvPrefix) {
        if (self.isNeedCreate) {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:linkPrefixAnotherHeaderId];
        } else {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:linkPrefixHeaderId];
        }
        header.controllerEnum = self.viewcontrollerEnum;
        header.linkHeaderList = self.tvPrefixHeaders;
    } else {
        if (self.isNeedCreate) {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:linkContentAnotherHeaderId];
        } else {
            header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:linkContentHeaderId];
        }
        header.controllerEnum = self.viewcontrollerEnum;
        header.linkHeaderList = self.tvContentHeaders;
        
    }
    return header;
}

//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
//    //
//    if (tableView == _tvPrefix) {
//        ((GXLinkCell *)cell).linkCellList = self.tvPrefixList[indexPath.row];
//    }else {
//        ((GXLinkCell *)cell).linkCellList = self.tvContentList[indexPath.row];
//    }
//}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _tvPrefix) {
        
        [_tvContent setContentOffset:scrollView.contentOffset animated:NO];
    } else { // _tvContent
        
        [_tvPrefix setContentOffset:scrollView.contentOffset animated:NO];
    }
    //    NSLog(@"%@", NSStringFromCGPoint(scrollView.contentOffset));
}

#pragma mark gesture delegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}


#pragma mark - setupUI
-(void) setupUI {
    //    self.view.backgroundColor = [UIColor redColor];
    //
    [self setTableViews];
    
    [self setGuidView];
    
    //pan
    UIPanGestureRecognizer *panHorizontal = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panHorizontalAction:)];
    [self.view addGestureRecognizer:panHorizontal];
    panHorizontal.delegate = self;
}

- (void)setTableViews {
    //tvPrefix
    UITableView *tvPrefix = [[UITableView alloc] init];
    [self.view addSubview:tvPrefix];
    
    [tvPrefix mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.equalTo(self.view).mas_offset(0);
        make.width.mas_offset([UIScreen mainScreen].bounds.size.width * 1/3);
    }];
    
    //svContent
    UIScrollView *svContent = [[UIScrollView alloc] init];
    [self.view addSubview:svContent];
    
    svContent.bounces = NO;
    svContent.showsVerticalScrollIndicator = NO;
    svContent.showsHorizontalScrollIndicator = NO;
    
    [svContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.trailing.equalTo(self.view).mas_offset(0);
        make.leading.equalTo(tvPrefix.mas_trailing).mas_offset(0);
    }];
    [self.view layoutIfNeeded];
    
    UIView *vSize = [[UIView alloc] init];
    [svContent addSubview:vSize];
    
#pragma mark vSize
    if ([vSize respondsToSelector:@selector(setLayoutMargins:)]) {
        [vSize setLayoutMargins:UIEdgeInsetsZero];
    }
    
    [vSize mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(svContent);
        make.width.mas_offset(10 * 80 + 5); //暂时设置，会根据数据源内容更新
        make.height.equalTo(self.view);
    }];
    
#pragma mark tvContent
    //tvContent
    UITableView *tvContent = [[UITableView alloc] init]; //WithFrame:CGRectZero style:UITableViewStyleGrouped];
    [vSize addSubview:tvContent];
    
    //    tvContent.backgroundColor = [UIColor orangeColor];
    
    [tvContent mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.trailing.equalTo(vSize).mas_offset(0);
    }];
    [self.view layoutIfNeeded];
    
    tvPrefix.dataSource = self;
    tvPrefix.delegate = self;
    tvContent.dataSource = self;
    tvContent.delegate = self;
    
    [tvPrefix registerClass:[GXLinkCell class] forCellReuseIdentifier:linkPrefixCellId];
    [tvPrefix registerClass:[GXLinkCell class] forCellReuseIdentifier:linkPrefixAnotherCellId];
    
    [tvContent registerClass:[GXLinkCell class] forCellReuseIdentifier:linkContentCellId];
    [tvContent registerClass:[GXLinkCell class] forCellReuseIdentifier:linkContentAnotherCellId];
    
    [tvPrefix registerClass:[GXLinkHeader class] forHeaderFooterViewReuseIdentifier:linkPrefixHeaderId];
    [tvPrefix registerClass:[GXLinkHeader class] forHeaderFooterViewReuseIdentifier:linkPrefixAnotherHeaderId];
    
    [tvContent registerClass:[GXLinkHeader class] forHeaderFooterViewReuseIdentifier:linkContentHeaderId];
    [tvContent registerClass:[GXLinkHeader class] forHeaderFooterViewReuseIdentifier:linkContentAnotherHeaderId];
    
    tvPrefix.allowsSelection = tvContent.allowsSelection = NO;
    tvPrefix.bounces = tvContent.bounces = NO;
    tvPrefix.showsVerticalScrollIndicator = tvContent.showsVerticalScrollIndicator = NO;
    
    tvPrefix.separatorStyle = tvContent.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //
    self.tvPrefix = tvPrefix;
    self.tvContent = tvContent;
    self.svContent = svContent;
    self.vSize = vSize;
}

- (void)setGuidView {
    CGSize gradientSize = CGSizeMake(70, headerHeight - 5);
    //GXGradientView
    GXGradientView *vGradientLeft = [[GXGradientView alloc] init];
    [self.view addSubview:vGradientLeft];
    self.vGradientLeft = vGradientLeft;
    
    //    vGradientLeft.backgroundColor = [UIColor redColor];
    
    [vGradientLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tvPrefix).mas_offset(3);
        make.leading.equalTo(self.tvPrefix.mas_trailing).mas_offset(0);
        make.size.mas_offset(gradientSize);
    }];
    [self.view layoutIfNeeded];
    vGradientLeft.gradientDirection = GradientDirectionLeft;
    
    //GXGradientView
    GXGradientView *vGradientRight = [[GXGradientView alloc] init];
    [self.view addSubview:vGradientRight];
    self.vGradientRight = vGradientRight;
    
    //    vGradientRight.backgroundColor = [UIColor redColor];
    
    [vGradientRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.top.equalTo(vGradientLeft).mas_offset(0);
        make.trailing.equalTo(self.view).mas_offset(0);
    }];
    
    [self.view layoutIfNeeded];
    vGradientRight.gradientDirection = GradientDirectionRight;
    
}




#pragma mark - setter & getter
- (void)setPrefixScale:(CGFloat)prefixScale {
    _prefixScale = prefixScale;
    
    [self.tvPrefix mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.equalTo(self.view).mas_offset(0);
        make.width.mas_offset([UIScreen mainScreen].bounds.size.width * _prefixScale);
    }];
}

//set linkDict
- (void)setLinkDict:(NSDictionary *)linkDict {
    _linkDict = linkDict;

    self.tvPrefixHeaders = linkDict[@"tvPrefixHeaders"];
    self.tvPrefixList = linkDict[@"tvPrefixList"];
    
    self.tvContentHeaders = linkDict[@"tvContentHeaders"];
    self.tvContentList = linkDict[@"tvContentList"];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reload];
    });
}

//set tvPrefix
- (void)setTvPrefixHeaders:(NSArray<NSString *> *)tvPrefixHeaders {
    _tvPrefixHeaders = tvPrefixHeaders;
    
    [self reloadTvs];
}

- (void)setTvPrefixList:(NSArray *)tvPrefixList {
    _tvPrefixList = tvPrefixList;
    
    [self reloadTvs];
}

//set tvContent
- (void)setTvContentHeaders:(NSArray<NSString *> *)tvContentHeaders {
    _tvContentHeaders = tvContentHeaders;
    
    if (tvContentHeaders == nil || tvContentHeaders.count == 0) {
        return;
    }
    [self.vSize mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(80 * tvContentHeaders.count + 3);
    }];
    
    [self reloadTvs];
}

- (void)setTvContentList:(NSArray *)tvContentList {
    _tvContentList = tvContentList;
    
    [self reloadTvs];
}

- (void)setContentSvwWidth:(CGFloat)contentSvwWidth {
    _contentSvwWidth = contentSvwWidth;
    
    if (_linkDict == nil) {
        return;
    }
    
    [self.vSize mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(contentSvwWidth);
    }];
}



@end
